<template>
  <div ref="imageWrapper">
    <div class="modelTitle"><h2>设备物资-供应商管理模型</h2></div>
    <a-card title="查询条件" class="search">
      <div class="table-page-search-wrapper">
        <a-form-model layout="inline" ref="ruleForm" :model="queryParam" :rules="rules" @keyup.enter.native="onSearch">
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-model-item label="审计单位" prop="orgName">
                <a-input v-model="queryParam.orgName" readOnly placeholder="请选择" @click.native="openOrganModel" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="6">
              <a-form-model-item label="任期时间" prop="arrayTime">
                <a-range-picker
                  v-model="queryParam.arrayTime"
                  format="yyyy-MM-DD"
                  value-format="yyyy-MM-DD"
                  @change="handleDatechange"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8" :offset="4">
              <span style="float: right; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="onSearch" icon="search" class="yellow_search_btn">查询</a-button>
                <a-button @click="searchReset" icon="reload" class="clear_btn">清除条件</a-button>
                <a-button
                  type="danger"
                  :loading="ydLoading"
                  @click="handleToYD1()"
                  icon="arrow-right"
                  style="margin-left: 18px"
                  >转疑点</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card style="margin-top: 20px">
      <a-tabs
        default-active-key="0"
        @change="handleRequst"
        v-model="activeKey"
        type="card"
        class="tabs_style"
        style="margin-top: 5px"
      >
        <a-tab-pane key="0" tab="违规数据">
          <a-table
            ref="table"
            size="middle"
            rowKey="listId"
            bordered
            :columns="columns1"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            @change="handleTableChange"
            :row-selection="rowSelection"
            class="antableClass"
            :scroll="{ x: 2000 }"
          >
            <span slot="merchName" slot-scope="text, record">
              <a @click="handleChangeCheckList(record)">{{ text }}</a>
            </span>
            <span slot="action" slot-scope="text, record">
              <a @click="CheckDetail(record)">详情</a>
              <a-divider type="vertical" />
              <a style="color: red" @click="handleToYD(record)">转疑点</a>
            </span>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="1" tab="供应商信息">
          <div style="margin:20px 0px">
            <a-upload
              name="file"
              :showUploadList="false"
              :multiple="false"
              :headers="tokenHeader"
              :action="importExcelUrl"
              @change="handleImportExcel"
              accept=".docx, .doc, .xlsx, .xls, .pdf, .jpeg, .png"
            >
              <a-button :disabled="queryParam.orgId == ''" :loading="upLoading" type="primary" icon="import">
                导入
              </a-button>
            </a-upload>
            <a-button type="primary" icon="download" @click="onDownLoad" style="margin: 0px 8px">
              模板下载
            </a-button>
          </div>
          <TbaleCom :reload="reloadCol2" :list="lists[1]" :columns="columns2" :param="queryParam" />
        </a-tab-pane>
        <a-tab-pane key="2" tab="限制供应商">
          <a-form-model layout="inline" :model="limitQueryParam" style="margin:20px 0px">
            <a-form-model-item label="供应商姓名" prop="arrayTime">
              <a-input v-model="limitQueryParam.name" placeholder="请选择限制供应商名称" />
            </a-form-model-item>
          </a-form-model>
          <TbaleCom :reload="reloadCol3" :list="lists[2]" :columns="columns3" :param="limitQueryParam" />
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <YDModel ref="YDModel" :routerData="$route.path" />
    <CheckDetail ref="CheckDetail" />
    <AuditDepart ref="AuditDepart" @selectedRow="updateQueryParam" />
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { columns1, columns2, columns3 } from './columns'
import { base64toImg } from '@/mixins/base64toImg'
import YDModel from './YDModel'
import html2canvas from 'html2canvas'
import CheckDetail from './CheckDetail.vue'
import TbaleCom from '@/views/sj/sjmxgl/gcxmgl/sbwzgys/TbaleCom'
import { httpAction, getAction, postAction, deleteAction, putAction } from '@/api/manage'
import { beforeyearY, currentY } from '@/mixins/commontime.js'
import AuditDepart from '@/views/sj/sjmxgl/cwzb/components/AuditDepart'
export default {
  mixins: [JeecgListMixin, base64toImg],
  components: { AuditDepart, YDModel, CheckDetail, TbaleCom },
  computed: {
    // 行选择
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = [...selectedRowKeys]
          this.selectedRows = [...selectedRows]
        }
      }
    },
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/sjmx/importMerch?orgId=${this.queryParam.orgId}`
    }
  },
  watch: {
    $route: {
      handler: function(to) {
        if (Object.keys(to.query).length) {
          this.disableMixinCreated = true
          console.log(to.query)
          this.selectedRowKeys = to.query.selectedRowKeys.split(',').map(item => parseInt(item)) || []
          to.query.selectedRowKeys && delete to.query.selectedRowKeys
          this.queryParam = Object.assign(this.queryParam, to.query)
          this.queryParam.arrayTime = to.query.arrayTime.split(',')
          this.$nextTick(() => {
            this.searchQuery()
          })
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      disableMixinCreated: true,
      columns1: columns1(this),
      columns2: columns2(this),
      columns3: columns3(this),
      queryParam: {
        orgName: '',
        orgId: '',
        startYear: beforeyearY(3, 'years'),
        endYear: currentY()
      },
      superParam: {
        id: 'e64079ce56a16f8c4cfc05519b63ewfs',
        modelId: 'e64079ce56a16f8c4cfc05519b63ewfs',
        extraFlag: true
      },
      upLoading: false,
      dataSource: [],
      limitQueryParam: {
        name: '',
        orgName: '',
        orgId: '',
        startYear: beforeyearY(3, 'years'),
        endYear: currentY()
      },
      url: {
        list: '/sjmx/queryViolationMerchData',
        // 查询模型转疑点信息(多选)
        TurnSuspects: '/sjmx/queryModelMsgMulti'
      },
      lists: ['/sjmx/queryViolationMerchData', '/sjmx/queryMerchData', '/sjmx/queryLimitMerchData'],
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 }
      },
      rules: {
        orgName: [{ required: true, message: '请选择审计单位' }],
        arrayTime: [{ required: true, message: '请选择审计时间' }]
      },
      activeKey: '0',
      reloadCol2: false,
      reloadCol3: false,
      // 日期显示
      yearPickShow: false,
      yearPickShow1: false,
      selectedRows: [],
      selectedRowKeys: []
    }
  },
  methods: {
    searchReset() {
      this.dataSource = []
      this.queryParam = this.$options.data().queryParam
    },
    openOrganModel() {
      this.$refs.AuditDepart.show()
    },
    CheckDetail(record) {
      this.$refs.CheckDetail.edit(record, this.queryParam)
    },
    onDownLoad() {
      this.$message.success('正在下载，请稍等！')
      let url = `${window._CONFIG['domianURL']}/sys/common/static/xls-template/import_merch.xlsx`
      window.open(url, '_blank')
    },
    handleChangeCheckList(record) {
      if (record.ifPassMerch.indexOf('是') != -1) {
        //  是，切换成 供应商信息
        this.activeKey = '1'
      } else {
        // 否，切换成 限制供应商
        this.activeKey = '2'
        this.limitQueryParam = Object.assign({}, this.limitQueryParam, { name: record.merchName }, this.queryParam)
        this.reloadCol3 = !this.reloadCol3
      }
    },
    updateQueryParam(checkRow) {
      console.log(checkRow)
      this.queryParam.orgName = checkRow.departName
      this.queryParam.orgId = checkRow.id
    },
    onSearch() {
      this.$refs.ruleForm.validate(value => {
        if (value) {
          // 根据tag 动态刷新
          switch (this.activeKey) {
            case '0':
              this.loadData(1)
              break
            case '1':
              this.reloadCol2 = !this.reloadCol2
              break
            case '2':
              this.limitQueryParam = Object.assign({}, this.limitQueryParam, { name: '' }, this.queryParam)
              this.reloadCol3 = !this.reloadCol3
              break
            default:
              break
          }
        } else {
          this.$message.warning('请选择审计单位和审计时间')
        }
      })
    },
    handleToYD(record) {
      if (this.dataSource.length) {
        const { startTime = '', endTime = '' } = this.queryParam
        let ydnr = record.wgxx
        const time = `【${startTime}～${endTime}】【设备物资-供应商管理】`

        this.addYd(this.queryParam, ydnr, time)
      } else {
        this.$message.error('空数据不能新建疑点')
      }
    },
    handleToYD1(record) {
      if (this.dataSource.length) {
        debugger
        const { startTime = '', endTime = '' } = this.queryParam
        let ydnr = undefined
        let gzzd = undefined

        let time = `【${startTime}～${endTime}】【设备物资-供应商管理】`
        console.log('this.activeKey------>', this.activeKey)
        let selectedRowKeys = this.selectedRows.map(item => item.listId)

        let param = Object.assign(
          {},
          this.queryParam,
          { activeKey: this.activeKey },
          { selectedRowKeys: selectedRowKeys.join(' ') }
        )
        let ydList = this.getselectRowJosn(this.selectedRows)
        console.log(ydList)
        postAction(this.url.TurnSuspects, Object.assign({}, this.queryParam, this.superParam, { ydList: ydList })).then(
          res => {
            if (res.success) {
              if (res.result.length) {
                ydnr = res.result[0].ydms ? res.result[0].ydms : ydnr
                gzzd = res.result[0].gzzd ? res.result[0].gzzd : gzzd
              }
              this.addYdMulti(param, ydnr, time, gzzd)
            }
            if (res.code === 510) {
              this.$message.warning(res.message)
            }
          }
        )
      } else {
        this.$message.error('空数据不能新建疑点')
      }
    },
    getselectRowJosn(selectedRows) {
      selectedRows.map(item => {
        item.zb = item.target
      })
      return JSON.stringify(selectedRows)
    },
    handleRequst(key) {
      this.activeKey = key
      this.onSearch()
    },
    handleDatechange(dates) {
      this.queryParam.startTime = dates[0]
      this.queryParam.endTime = dates[1]
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@assets/less/tableTheme.less';
.modelTitle {
  display: flex;
  justify-content: center;
  align-items: center;
  h2 {
    font-weight: 600;
  }
}
</style>
